package com.ifdom.thread.threadpool;

import java.util.concurrent.*;

/**
 * 自定义线程池构造器
 * 自定义构造器可以设置线程名称以及优先级
 *
 * @Author ifredomvip@gmail.com
 * @Date 2022/10/4 16:55
 * @Version 1.0.0
 * @Description
 **/
public class DefineThreadPoolFactory {
    public static void main(String[] args) {

        ThreadFactory defineThreadFactory = new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                System.out.println("创建线程: " + r.hashCode() + " ");
                //线程命名
                Thread th = new Thread(r, "threadPool" + r.hashCode());
                String threadName = th.getName();
                System.out.println("线程名称: "+threadName);
                return th;
            }
        };

        ExecutorService executorService = new ThreadPoolExecutor(0,
                2,
                300,
                TimeUnit.SECONDS,
                new SynchronousQueue<>(),
                defineThreadFactory,
                new ThreadPoolExecutor.AbortPolicy()
        );

        Runnable task = () -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        executorService.execute(task);
    }
}
